package com.alstudio.utils.android.net.http.http2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import com.alstudio.utils.android.net.IoUtils;

import android.text.TextUtils;

public class HttpUtils {

	private static final int IO_BUFFER_SIZE = 1024;

	public static String encodeParameters(HttpParameters httpParams) {
		if (null == httpParams || httpParams.isEmpty()) {
			return "";
		}

		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (int loc = 0; loc < httpParams.size(); loc++) {
			String key = httpParams.getKey(loc);
			if (first) {
				first = false;
			} else {
				sb.append("&");
			}

			try {
				sb.append(URLEncoder.encode(key, "UTF-8"))
						.append("=")
						.append(URLEncoder.encode(httpParams.getValue(key),
								"UTF-8"));
			} catch (UnsupportedEncodingException neverHappen) {
			}
		}

		return sb.toString();
	}

	public static String readHttpResponseBody(HttpResponse response)
			throws IOException {
		if (response == null)
			return null;

		String charset = null;
		Header contentEncoding = response.getEntity().getContentEncoding();
		if (contentEncoding != null) {
			charset = contentEncoding.getValue();
		}

		if (TextUtils.isEmpty(charset))
			charset = "UTF-8";

		InputStream is = null;
		final StringWriter writer = new StringWriter();
		final char[] buf = new char[IO_BUFFER_SIZE];
		try {
			is = response.getEntity().getContent();
			final Reader reader = new BufferedReader(new InputStreamReader(is,
					charset));
			int read;
			while ((read = reader.read(buf)) != -1) {
				writer.write(buf, 0, read);
			}

		} finally {
			IoUtils.closeStream(is);
		}

		String text = writer.toString();
		writer.close();

		return text;
	}
}
